'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  const { userA, userB, page = 1, pageSize = 50 } = event;

  if (!userA || !userB) {
    return {
      code: 400,
      msg: '缺少用户ID参数'
    };
  }

  try {
    // 查询两个用户之间的聊天消息
    const collection = db.collection('chatMessages');
    
    // 查询条件：发送者和接收者分别是userA和userB，或者相反
    const whereCondition = {
      $or: [
        {
          senderId: userA,
          receiverId: userB
        },
        {
          senderId: userB,
          receiverId: userA
        }
      ]
    };

    // 获取总数
    const totalRes = await collection.where(whereCondition).count();
    const total = totalRes.total;

    // 获取消息列表
    const res = await collection
      .where(whereCondition)
      .orderBy('createTime', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get();

    // 返回消息列表（按时间正序）
    const messages = res.data.reverse().map(item => ({
      _id: item._id,
      type: item.type,
      senderId: item.senderId,
      senderAvatar: item.senderAvatar,
      senderNickname: item.senderNickname,
      receiverId: item.receiverId,
      receiverAvatar: item.receiverAvatar,
      receiverNickname: item.receiverNickname,
      content: item.content,
      createTime: item.createTime,
      status: item.status || 'sent',
      title: item.title, // 交易卡片的标题
      taskId: item.taskId,
      imageUrl: item.imageUrl,
      location: item.location
    }));

    return {
      code: 200,
      msg: '获取聊天消息成功',
      data: messages,
      total: total,
      page: page,
      pageSize: pageSize
    };
  } catch (error) {
    console.error('获取聊天消息失败:', error);
    return {
      code: 500,
      msg: '服务器错误',
      error: error.message
    };
  }
};